package kz.kstu.scantest.business.client.key;

import kz.kstu.scantest.business.entity.Key;
import kz.kstu.scantest.business.util.DateUtil;
import kz.kstu.scantest.business.util.NumberUtil;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

/**
 * @author Filipp_Stankevich
 *         created 01.09.12 20:43
 */
public class KeyXmlParser extends DefaultHandler {

    private Key key;
    private String currentElement;

    public Key parse (String xml) throws IOException, SAXException {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(this);
        StringReader stringReader = new StringReader(xml);
        InputSource source = new InputSource(stringReader);
        reader.parse(source);
        return key;
    }

    @Override
    public void startDocument () throws SAXException {
        key = new Key();
    }

    @Override
    public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException {
        currentElement = localName;
    }

    @Override
    public void characters (char ch[], int start, int length) throws SAXException {
        String value = new String(ch, start, length);
        if (KeyXmlTag.NUMBER.equals(currentElement)) {
            key.setNumber(value);
        } else if (KeyXmlTag.WRITE_OFF_COUNT.endsWith(currentElement)) {
            key.setWriteOffCount(NumberUtil.parseInt(value));
        } else if (KeyXmlTag.MAX_COUNT.endsWith(currentElement)) {
            key.setMaxCount(NumberUtil.parseInt(value));
        } else if (KeyXmlTag.EXPIRY_DATE.endsWith(currentElement)) {
            key.setExpiryDate(DateUtil.parseDate(value, DateUtil.SIMPLE_DATE_PATTERN));
        } else if (KeyXmlTag.DIGEST.endsWith(currentElement)) {
            key.setDigest(value);
        }
    }

}
